<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Watermark System</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        :root {
            --primary-color: #4a90e2;
            --secondary-color: #f5f5f5;
            --text-color: #333;
            --border-radius: 8px;
        }

        body {
            background-color: var(--secondary-color);
            color: var(--text-color);
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        .main-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 2rem;
            background-color: white;
            border-radius: var(--border-radius);
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        .page-title {
            color: var(--primary-color);
            font-weight: 600;
            margin-bottom: 2rem;
            text-align: center;
            font-size: 2.5rem;
        }

        .nav-tabs {
            border-bottom: 2px solid var(--primary-color);
            margin-bottom: 2rem;
        }

        .nav-tabs .nav-link {
            border: none;
            color: var(--text-color);
            font-weight: 500;
            padding: 1rem 2rem;
            border-radius: var(--border-radius) var(--border-radius) 0 0;
            transition: all 0.3s ease;
        }

        .nav-tabs .nav-link:hover {
            background-color: rgba(74, 144, 226, 0.1);
        }

        .nav-tabs .nav-link.active {
            color: white;
            background-color: var(--primary-color);
        }

        .form-container {
            background-color: white;
            padding: 2rem;
            border-radius: var(--border-radius);
            margin-bottom: 2rem;
        }

        .preview-container {
            position: relative;
            border: 2px dashed #ddd;
            border-radius: var(--border-radius);
            padding: 1rem;
            text-align: center;
            margin: 1rem 0;
            min-height: 200px;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction: column;
            transition: all 0.3s ease;
        }

        .preview-container:hover {
            border-color: var(--primary-color);
        }

        .preview-image {
            max-width: 100%;
            max-height: 300px;
            margin: 1rem 0;
            border-radius: var(--border-radius);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        .form-label {
            font-weight: 500;
            color: var(--text-color);
            margin-bottom: 0.5rem;
        }

        .form-range {
            height: 6px;
            border-radius: 3px;
        }

        .form-range::-webkit-slider-thumb {
            background: var(--primary-color);
        }

        .btn-primary {
            background-color: var(--primary-color);
            border: none;
            padding: 0.8rem 2rem;
            font-weight: 500;
            border-radius: var(--border-radius);
            transition: all 0.3s ease;
        }

        .btn-primary:hover {
            background-color: #357abd;
            transform: translateY(-1px);
        }

        .loading {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(255, 255, 255, 0.9);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }

        .loading-content {
            text-align: center;
        }

        .loading .spinner-border {
            width: 3rem;
            height: 3rem;
        }

        .parameter-info {
            font-size: 0.9rem;
            color: #666;
            margin-top: 0.5rem;
        }

        .upload-icon {
            font-size: 3rem;
            color: #ddd;
            margin-bottom: 1rem;
        }

        .result-container {
            background-color: #f8f9fa;
            padding: 2rem;
            border-radius: var(--border-radius);
            margin-top: 2rem;
        }

        .alert {
            display: none;
            margin-top: 1rem;
        }

        @media (max-width: 768px) {
            .main-container {
                padding: 1rem;
            }

            .nav-tabs .nav-link {
                padding: 0.8rem 1rem;
            }

            .form-container {
                padding: 1rem;
            }
        }

        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }
        
        .loading-spinner {
            color: white;
            font-size: 24px;
        }
        
        .loading-text {
            color: white;
            margin-left: 10px;
            font-size: 18px;
        }
    </style>
</head>
<body>
    <div class="loading-overlay">
        <div class="d-flex align-items-center">
            <div class="spinner-border loading-spinner" role="status"></div>
            <span class="loading-text">Processing image, please wait...</span>
        </div>
    </div>
    
    <div class="main-container mt-4">
        <h1 class="page-title">
            <i class="fas fa-image me-2"></i>
            Image Watermark System
        </h1>
        
        <!-- Tabs -->
        <ul class="nav nav-tabs" id="operationTabs" role="tablist">
            <li class="nav-item">
                <a class="nav-link active" id="embed-tab" data-bs-toggle="tab" href="#embed" role="tab">
                    <i class="fas fa-plus-circle me-2"></i>Embed Watermark
                </a>
            </li>
            <!-- <li class="nav-item">
                <a class="nav-link" id="extract-tab" data-bs-toggle="tab" href="#extract" role="tab">
                    <i class="fas fa-search me-2"></i>Extract Watermark
                </a>
            </li> -->
        </ul>
        
        <!-- Tab Content -->
        <div class="tab-content">
            <!-- Embed Watermark Tab -->
            <div class="tab-pane fade show active" id="embed" role="tabpanel">
                <form id="embedForm" class="form-container">
                    <div class="mb-4">
                        <label for="originalImage" class="form-label">Original Image</label>
                        <div class="preview-container" id="originalImageContainer">
                            <i class="fas fa-cloud-upload-alt upload-icon"></i>
                            <input type="file" class="form-control" id="originalImage" name="originalImage" accept="image/*" required>
                            <img id="originalPreview" class="preview-image" style="display: none;">
                            <div class="parameter-info">Supported formats: JPG, PNG, BMP</div>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label for="watermarkText" class="form-label">Watermark Text</label>
                        <input type="text" class="form-control" id="watermarkText" name="watermarkText" required>
                        <div class="parameter-info">Enter the text you want to use as watermark</div>
                    </div>

                    <div class="mb-3">
                        <label for="watermarkFont" class="form-label">Font</label>
                        <select class="form-select" id="watermarkFont" name="watermarkFont">
                            <option value="Arial">Arial</option>
                            <option value="Times New Roman">Times New Roman</option>
                            <option value="Courier New">Courier New</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label for="fontSize" class="form-label">Font Size</label>
                        <input type="range" class="form-range" id="fontSize" name="fontSize" min="12" max="72" value="32">
                        <div class="parameter-info">Font size: <span id="fontSizeValue">32</span>px</div>
                    </div>

                    <div class="mb-3">
                        <label for="opacity" class="form-label">Opacity</label>
                        <input type="range" class="form-range" id="opacity" name="opacity" min="0" max="1" step="0.1" value="0.5">
                        <div class="parameter-info">Opacity: <span id="opacityValue">0.5</span></div>
                    </div>

                    <div class="mb-3">
                        <label for="angle" class="form-label">Rotation Angle</label>
                        <input type="range" class="form-range" id="angle" name="angle" min="-45" max="45" value="0">
                        <div class="parameter-info">Angle: <span id="angleValue">0</span>°</div>
                    </div>

                    <div class="mb-3">
                        <label for="density" class="form-label">Density</label>
                        <input type="range" class="form-range" id="density" name="density" min="0.5" max="2.0" step="0.1" value="1.0">
                        <div class="parameter-info">Density: <span id="densityValue">1.0</span></div>
                    </div>

                    <div class="mb-3">
                        <label for="quality" class="form-label">Image Quality</label>
                        <input type="range" class="form-range" id="quality" name="quality" min="1" max="100" value="90">
                        <div class="parameter-info">Quality: <span id="qualityValue">90</span>%</div>
                    </div>

                    <button type="submit" class="btn btn-primary w-100">
                        <i class="fas fa-magic me-2"></i>Apply Watermark
                    </button>
                </form>
                
                <div id="embedResult" class="result-container" style="display: none;">
                    <h4><i class="fas fa-check-circle me-2"></i>Result:</h4>
                    <img id="watermarkedPreview" class="preview-image">
                    <div class="text-center mt-3">
                        <a id="downloadWatermarked" class="btn btn-primary" download>
                            <i class="fas fa-download me-2"></i>Download Watermarked Image
                        </a>
                    </div>
                </div>
            </div>
            
            <!-- Extract Watermark Tab -->
            <div class="tab-pane fade" id="extract" role="tabpanel">
                <form id="extractForm" class="form-container">
                    <div class="mb-4">
                        <label for="watermarkedImage" class="form-label">Watermarked Image</label>
                        <div class="preview-container" id="watermarkedImageContainer">
                            <i class="fas fa-cloud-upload-alt upload-icon"></i>
                            <input type="file" class="form-control" id="watermarkedImage" name="image" accept="image/*" required>
                            <img id="watermarkedImagePreview" class="preview-image" style="display: none;">
                            <div class="parameter-info">Upload an image that contains a watermark</div>
                        </div>
                    </div>
                    
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="fas fa-search me-2"></i>Extract Watermark
                    </button>
                </form>
                
                <div id="extractResult" class="result-container" style="display: none;">
                    <h4><i class="fas fa-check-circle me-2"></i>Extraction Result</h4>
                    <div class="mt-3">
                        <div id="extractedText" class="p-3 bg-light border rounded">
                            <strong>Extracted Text:</strong> <span class="extracted-content"></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Alert Messages -->
        <div class="alert alert-success" role="alert">
            <i class="fas fa-check-circle me-2"></i>
            <span class="alert-message"></span>
        </div>
        <div class="alert alert-danger" role="alert">
            <i class="fas fa-exclamation-circle me-2"></i>
            <span class="alert-message"></span>
        </div>

        <!-- Loading Spinner -->
        <div class="loading">
            <div class="loading-content">
                <div class="spinner-border text-primary mb-3" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
                <p class="mb-0">Processing your image...</p>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script>
        // Show alert message
        function showAlert(message, type = 'success') {
            const alertElement = document.querySelector(`.alert-${type}`);
            alertElement.querySelector('.alert-message').textContent = message;
            alertElement.style.display = 'block';
            setTimeout(() => {
                alertElement.style.display = 'none';
            }, 5000);
        }

        // Preview image uploads
        function previewImage(input, previewId, containerId) {
            const preview = document.getElementById(previewId);
            const container = document.getElementById(containerId);
            const uploadIcon = container.querySelector('.upload-icon');

            if (input.files && input.files[0]) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    preview.src = e.target.result;
                    preview.style.display = 'block';
                    uploadIcon.style.display = 'none';
                };
                reader.readAsDataURL(input.files[0]);
            } else {
                preview.style.display = 'none';
                uploadIcon.style.display = 'block';
            }
        }

        // Setup preview handlers
        document.getElementById('originalImage').addEventListener('change', function() {
            previewImage(this, 'originalPreview', 'originalImageContainer');
        });
        document.getElementById('watermarkedImage').addEventListener('change', function() {
            previewImage(this, 'watermarkedImagePreview', 'watermarkedImageContainer');
        });

        // Update parameter value displays
        document.getElementById('opacity').addEventListener('input', function() {
            document.getElementById('opacityValue').textContent = this.value;
        });
        
        document.getElementById('fontSize').addEventListener('input', function() {
            document.getElementById('fontSizeValue').textContent = this.value;
        });
        
        document.getElementById('angle').addEventListener('input', function() {
            document.getElementById('angleValue').textContent = this.value;
        });
        
        document.getElementById('density').addEventListener('input', function() {
            document.getElementById('densityValue').textContent = this.value;
        });
        
        document.getElementById('quality').addEventListener('input', function() {
            document.getElementById('qualityValue').textContent = this.value;
        });

        // Handle form submission
        document.getElementById('embedForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData();
            formData.append('originalImage', document.getElementById('originalImage').files[0]);
            formData.append('watermarkText', document.getElementById('watermarkText').value);
            formData.append('watermarkFont', document.getElementById('watermarkFont').value);
            formData.append('fontSize', parseInt(document.getElementById('fontSize').value));
            formData.append('color', '#a84343');
            formData.append('angle', parseInt(document.getElementById('angle').value));
            formData.append('opacity', parseFloat(document.getElementById('opacity').value));
            formData.append('density', parseFloat(document.getElementById('density').value));
            formData.append('quality', parseInt(document.getElementById('quality').value));
            
            // Show loading overlay
            document.querySelector('.loading-overlay').style.display = 'flex';
            
            fetch('/api/watermark/embed', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.watermarkedImageUrl) {
                    const resultContainer = document.createElement('div');
                    resultContainer.className = 'result-container mt-4';
                    resultContainer.innerHTML = `
                        <h4>Result</h4>
                        <img src="${data.watermarkedImageUrl}" class="img-fluid rounded" alt="Watermarked Image">
                        <div class="mt-2">
                            <p>Similarity: ${(data.similarity * 100).toFixed(2)}%</p>
                            <p>Processing Time: ${data.processingTime}ms</p>
                        </div>
                        <a href="${data.watermarkedImageUrl}" class="btn btn-primary" download>
                            <i class="fas fa-download me-2"></i>Download
                        </a>
                    `;
                    
                    // Remove any existing result container
                    const existingResult = document.querySelector('.result-container');
                    if (existingResult) {
                        existingResult.remove();
                    }
                    
                    // Add new result container
                    document.getElementById('embedForm').after(resultContainer);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Failed to process watermark: ' + error.message);
            })
            .finally(() => {
                // Hide loading overlay
                document.querySelector('.loading-overlay').style.display = 'none';
            });
        });

        // Extract watermark form submission
        document.getElementById('extractForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            // Validate file input
            const watermarkedImage = document.getElementById('watermarkedImage').files[0];
            
            if (!watermarkedImage) {
                showAlert('Please select an image to extract watermark from.', 'danger');
                return;
            }
            
            const formData = new FormData();
            formData.append('image', watermarkedImage);

            try {
                document.querySelector('.loading-overlay').style.display = 'flex';
                document.querySelector('.loading-text').textContent = 'Extracting watermark... This may take a few moments.';
                
                const response = await axios.post('/api/watermark/extract', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    },
                    timeout: 120000 // 120 seconds timeout
                });
                
                const data = response.data;
                console.log('Response data:', data); // 添加调试日志
                
                if (data) {
                    // 显示提取的文本
                    const extractedContent = document.querySelector('#extractedText .extracted-content');
                    if (data.extractedText && data.extractedText.trim()) {
                        extractedContent.textContent = data.extractedText;
                    } else {
                        extractedContent.textContent = 'No text was detected';
                    }
                    
                    // 显示结果容器
                    document.getElementById('extractResult').style.display = 'block';
                    
                    showAlert('Watermark text extraction completed');
                } else {
                    showAlert('Failed to extract watermark: Invalid response from server', 'danger');
                }
            } catch (error) {
                console.error('Error:', error);
                let errorMessage;
                
                if (error.response && error.response.data && error.response.data.message) {
                    errorMessage = error.response.data.message;
                } else if (error.code === 'ECONNABORTED') {
                    errorMessage = 'Request timed out. Please try again.';
                } else if (error.request) {
                    errorMessage = 'Server is not responding. Please try again later.';
                } else {
                    errorMessage = 'An error occurred while extracting the watermark.';
                }
                
                showAlert(errorMessage, 'danger');
            } finally {
                document.querySelector('.loading-overlay').style.display = 'none';
            }
        });

        // Reset result containers when switching tabs
        document.querySelectorAll('a[data-bs-toggle="tab"]').forEach(tab => {
            tab.addEventListener('shown.bs.tab', function (e) {
                document.getElementById('embedResult').style.display = 'none';
                document.getElementById('extractResult').style.display = 'none';
            });
        });
    </script>
</body>
</html> 